package com.me.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.me.annotation.Admin;
import com.me.annotation.Authorize;
import com.me.model.User;
import com.me.model.normal.NormalUser;
import com.me.services.IUserService;
import com.me.services.ServiceManager;
import org.apache.commons.fileupload.FileItem;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author 吕旺平
 * @date 2019/10/20 16:39:54
 * @description
 */
public class UserController extends Controller{
	IUserService<User> uServ = ServiceManager.getUserService();
	
	public UserController(HttpServletRequest req, HttpServletResponse resp) {
		super(req, resp);
	}
	
	public String login(){
		//获取验证码
		String userVerifyCode = getParam("verify");
		String verifyCode = (String)getSessionAttr("KAPTCHA_SESSION_KEY");
		String errMsg = null;//定义错误信息
		if (userVerifyCode.equals(verifyCode) || true){//验证验证码
			//验证用户
			String uName = getParam("uName");
			String pwd = getParam("pwd");
			if (uServ.isUserCanLogin(uName,pwd)){
				User u = uServ.login(uName,pwd);
				setSessionAttr("user", u);
				return "./index.jsp";
			}else{
				errMsg = "用户名或密码错误";
			}
		}else{
			errMsg = "验证码错误";
		}
		setReqAttr("errMsg",errMsg);
		return "/user/login.jsp";
	}
	
	public String register(){
		String uName = getParam("username");
		String pwd = getParam("password");
//		String name = getParam("name");
//		String sex = getParam("sex");
		String email = "";
		String name = "default";
		String sex = "1";
		String mobile = "";
		
		IUserService uServ = ServiceManager.getUserService();
		if(uServ.isUserExist(uName)){
			setReqAttr("error","用户已存在");
			return "/user/register.jsp";
		}
		//TODO 头像
		boolean isOk = uServ.addUser(
				new NormalUser(UUID.randomUUID().toString(),email,uName,
						pwd,"",name,Integer.parseInt(sex),mobile)
		);
		if (isOk){
			return "./user/login.jsp";
		} else{
			setReqAttr("error","用户注册失败");
			return "/user/register.jsp";
		}
	}
	
	@Authorize
	public String updateInfo(){
		NormalUser u = (NormalUser)getSessionAttr("user");
		String savePath = req.getServletContext().getRealPath("/img/upload");
		File file = new File(savePath);
		if (!file.exists() && !file.isDirectory()) {
			file.mkdir();
		}
		try {
			List<FileItem> items = (List<FileItem>)getReqAttr("items");
			removeReqAttr("items");
			for (FileItem item : items){
				if (item.isFormField()){
					if (item.getFieldName().equals("name")) {
						u.setName(item.getString("utf8"));
					} else if (item.getFieldName().equals("sex")) {
						u.setSex(Integer.parseInt(item.getString("utf8")));
					}
				}else{
					if (item.getInputStream().available() > 0){
						Date date = new Date();
						String fileName = date.hashCode() + item.getName().substring(item.getName().lastIndexOf("."));
						String fullName = savePath + "/" + fileName;
						InputStream in = item.getInputStream();
						FileOutputStream out = new FileOutputStream(fullName);
						byte[] buffer = new byte[1024];
						int len = 0;
						while ((len = in.read(buffer)) > 0){
							out.write(buffer,0,len);
						}
						in.close();
						out.close();
						item.delete();
						u.setHeadPath("/img/upload/" + fileName);
					}
				}
			}
			uServ.update(u);
		}catch (IOException e) {
			e.printStackTrace();
		}
		
		return "./index.jsp";
	}
	
	@Authorize
	public String logout(){
		setSessionAttr("user",null);
		return "./index.jsp";
	}
	
	@Admin
	public String manage(){
		Collection<User> users = uServ.getAll();
		setReqAttr("users",users);
		return "/admin/UserManage.jsp";
	}
	
	@Admin
	public String edit(){
		String id = getParam("id");
		setReqAttr("u",uServ.getById(id));
		return "/admin/UserEdit.jsp";
	}
	
	@Admin
	public String delete(){
		String id = getParam("id");
		if (getSessionUser().getId().equals(id)){
			setRedirectParam("msg","不能删除自己",true);
		}else{
			uServ.remove(id);
		}
		return redirectToAction("manage");
	}

	@Admin
	public String update(){
		String id = getParam("id");
		String username = getParam("username");
		String email = getParam("email");
		String name = getParam("name");
		String mobile = getParam("mobile");
		int sex = getIntegerParam("sex");
		boolean admin = getBooleanParam("admin");

		NormalUser u = uServ.getById(id);

		if (getSessionUser().getId().equals(id) && getSessionUser().isAdmin() != admin){
			setRedirectParam("msg","不能修改自己的权限",true);
		}else{
			u.setUsername(username);
			u.setEmail(email);
			u.setName(name);
			u.setMobile(mobile);
			u.setSex(sex);
			u.setAdmin(admin);

			uServ.update(u);
			if (getSessionUser().getId().equals(id)) {
				setSessionAttr("user",u);
			}
		}

		return redirectToAction("manage");
	}

	@Admin
	public String add(){
		String username = getParam("username");
		String pwd = getParam("pwd");
		String email = getParam("email");
		String name = getParam("name");
		String mobile = getParam("mobile");
		int sex = getIntegerParam("sex");
		boolean admin = getBooleanParam("email");

		NormalUser u = new NormalUser("",email,username,pwd,"",name,sex,mobile);
		if (uServ.isUserExist(u.getUsername())){
			setRedirectParam("msg","重复的用户名，用户添加失败",true);
		}else{
			uServ.addUser(u,admin);
		}

		return redirectToAction("manage");
	}
	
	@Override
	public String excute() {
		return null;
	}
}
